package jdbc;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class DBUtils {
	// 设计单例模式
	private static Connection conn = null;
	private static Properties props = null;

	public DBUtils() {
	}

	static {
		props = new Properties();
		try {
			props.load(DBUtils.class.getResourceAsStream("/dbconf.properties"));
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		try {
			Class.forName(props.getProperty("jdbc.driverClass"));
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	public static synchronized Connection getConn() {
		try {
			if (conn == null) {
				conn = DriverManager.getConnection(props.getProperty("jdbc.url"), props.getProperty("jdbc.username"),
						props.getProperty("jdbc.password"));
			} else {
				return conn;
			}

		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}

	public void closeConn() {
		try {
			if (conn != null)
				conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

}
